import { QueryTypes } from "sequelize";
import { sequelize } from "../lib/database.js";
import logger from "../lib/log4js.js";


class WeightValueChecker {

    async findAddedScoreValue(project_id: string, form_id: string): Promise<number> {
        return this._findAddedScoreValue(project_id, form_id);
    }

    /***
     * 对表单某表单中未提交投票用户进行补分
     * 
     */
    async _findAddedScoreValue(project_id: string, form_id: string) {

        const sql = `
    select
     ifnull (sum(ifnull (rfot.weight_value, 0) / 10), 0) added_value
    from
    ru_form_owner_type rfot
    inner join (
        select
            rfot.form_id ru_form_id,
            rfot.type_id
        from
            ru_form_owner_type rfot
            inner join ru_form rf on rf.id = rfot.form_id
            inner join  eva_project ep ON ep.id= ?
        where
            rfot.form_id = ? and rfot.group_type = ep.group_type
        except
        select
            ea.rule_form_id,
            on2.type_id
        from
            eva_answer ea
            inner join eva_project_owner epo on epo.id = ea.project_owner_id
            inner join owner_name on2 on on2.id = epo.owner_name_id
        where
            ea.project_id = ?
            and rule_form_id = ?
        group by
            rule_form_id,
            on2.type_id
    ) uf on uf.ru_form_id = rfot.form_id
    and uf.type_id = rfot.type_id
    group by form_id
        `


        try {
            const result: any = await sequelize.query(sql, {
                replacements: [project_id, form_id, project_id, form_id],
                type: QueryTypes.SELECT
            })
            const logResult = {
                project_id,
                form_id,
                result
            }
            logger.info(`计算附加分 ${JSON.stringify(logResult)} `)
            return result.length > 0 ? result[0].added_value : 0;
        } catch (error) {
            logger.error(error);
        }
    }


}

export { WeightValueChecker }